#include <graphics.h>
#include "circle.h"
#include <conio.h>
#include <vector>
#include <iostream>
#include "point.h"
#include "fill.h"
using namespace std;

vector<Point> getfiblist(const Point &start, int size, int d);

void listenfill();

int main()
{
    initgraph(640, 480);
    setbkcolor(WHITE);
    cleardevice();
    setlinecolor(BLACK);
    int size, d;
    Point pos;
    cin >> size >> d >> pos.x >> pos.y;
    auto ps = getfiblist(pos, size, d);
    int a = d, b = d;

    DIRECTION dirs[4] = {LD, RD, RU, LU};
    for (size_t i = 0; i < ps.size(); ++i)
    {
        MD_Circle(ps[i].x, ps[i].y, b, BLACK, dirs[i % 4]);
        switch (dirs[i % 4])
        {
        case DIRECTION::LD:
            line(ps[i].x, ps[i].y, ps[i].x - b, ps[i].y);
            line(ps[i].x, ps[i].y, ps[i].x, ps[i].y + b);
            break;
        case DIRECTION::LU:
            line(ps[i].x, ps[i].y, ps[i].x - b, ps[i].y);
            line(ps[i].x, ps[i].y, ps[i].x, ps[i].y - b);
            break;
        case DIRECTION::RD:
            line(ps[i].x, ps[i].y, ps[i].x + b, ps[i].y);
            line(ps[i].x, ps[i].y, ps[i].x, ps[i].y + b);
            break;
        case DIRECTION::RU:
            line(ps[i].x, ps[i].y, ps[i].x + b, ps[i].y);
            line(ps[i].x, ps[i].y, ps[i].x, ps[i].y - b);
            break;
        }
        swap(a, b);
        b += a;
    }

    listenfill();
    closegraph();
    return 0;  
}

vector<Point> getfiblist(const Point &start, int size, int d)
{
    int x = start.x, y = start.y; // 设置起始点坐标
    int a = 0, b = d;             // 初始化斐波那契数列前两项
    int dir[4][4] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
    vector<Point> ce;
    ce.push_back(start);

    for (int i = 0; i < size; i++)
    {
        int nx = x + b * dir[i % 4][0]; // 计算下一个点的横坐标
        int ny = y + b * dir[i % 4][1]; // 计算下一个点的纵坐标

        x = nx; // 将当前点更新为下一个点
        y = ny;
        ce.emplace_back(x, y);

        int temp = a; // 更新斐波那契数列的值
        a = b;
        b += temp;
    }
    return ce;
}

void listenfill()
{
    ExMessage m;
    COLORREF colors[6] = {RED, BLUE, GREEN, YELLOW, CYAN, MAGENTA};
    int i = 0;
    while (true)
    {
        m = getmessage(EX_MOUSE | EX_KEY);
        switch (m.message)
        {
        case WM_LBUTTONDOWN:
            cout << "LB " << m.x << ", " << m.y << endl;
            myfloodfill({m.x, m.y}, colors[i], BLACK);
            i = (i + 1) % 6;
            break;
        case WM_RBUTTONDOWN:
            cout << "RB " << m.x << ", " << m.y << endl;
            myfloodfill({m.x, m.y}, WHITE, BLACK);
            break;
        case WM_KEYDOWN:
            cout << "EXIT" << endl;
            return;
        }
    }
}